package cn.tedu.lbs.basic.web.service;

import cn.tedu.lbs.basic.web.repository.UserRepository;
import cn.tedu.lbs.basic.web.util.AuthenticationContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.basic.util.RandomUserName;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.dto.UserDTO;
import com.tarena.lbs.pojo.basic.param.UserParam;
import com.tarena.lbs.pojo.basic.po.UserPO;
import com.tarena.lbs.pojo.basic.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public void register(UserParam userParam) throws BusinessException {
        //1.保证住的用户 手机号不重复注册
        checkPhone(userParam.getPhone());
        //2.新增创建user表格的一条数据
        saveUser(userParam);
    }

    private void saveUser(UserParam userParam) {
        //param转化成po 补充缺少属性保证新增insert成功
        UserPO po=new UserPO();
        BeanUtils.copyProperties(userParam,po);//phone password
        //1.状态 status初始化0 刚刚注册
        po.setStatus(0);
        //2.nickname username 用户暂时没有填写 使用一个随机名称
        String randomName = RandomUserName.createRandomName();
        po.setNickName(randomName);
        po.setUserName(randomName);
        //3.入住时间
        po.setRegTime(new Date());
        userRepository.save(po);
    }

    private void checkPhone(String phone) throws BusinessException {
        //select count(*) from lbs_user where phone=?
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("phone",phone);
        long count = userRepository.count(queryWrapper);
        Asserts.isTrue(count>0,new BusinessException("-2","手机号重复"));
    }

    public UserVO detail() throws BusinessException {
        Integer id=getUserId();
        UserPO po = userRepository.getById(id);
        Asserts.isTrue(po==null,new BusinessException("-2","登录用户根本不存在"));

        UserVO vo=new UserVO();
        BeanUtils.copyProperties(po,vo);
        return vo;
    }

    private Integer getUserId() throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        return userPrinciple.getId();
    }

    public UserDTO detail(Integer userId) throws BusinessException {
        UserPO po = userRepository.getById(userId);
        Asserts.isTrue(po==null,new BusinessException("-2","用户不存在"));
        UserDTO dto=new UserDTO();
        BeanUtils.copyProperties(po,dto);
        return dto;
    }
}
